// 子模块moduleA路径：store/modules/moduleA.js
export default {
	state: {
		text:"我是cart模块下state.text的值",
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cartInfo:JSON.parse(uni.getStorageSync('cartInfo')||'[]'),
	},
	getters: {
        total(state){
			return state.cartInfo.reduce((previousValue, currentValue)=> {
				return previousValue+currentValue.goods_count
			},0)
		},
		checkedCount(state){
			return state.cartInfo.filter(item=>item.goods_state).reduce((count,item)=>count+item.goods_count,0)
		},
			
		checkedGoodsPriceCount(state){
			return state.cartInfo.filter(item =>item.goods_state).reduce((total,item)=>total+item.goods_price*item.goods_count,0).toFixed(2)
		}
	},
	mutations: {
		updateCheckedState(state,status){
			state.cartInfo.forEach(item=>
				item.goods_state = status
			)
			this.commit('saveToStorage')
		},
		saveToStorage(state){
			uni.setStorageSync('cartInfo',JSON.stringify(state.cartInfo))
		},
        addToCart(state,goods){
			let findResult = state.cartInfo.find((item)=> item.goods_id === goods.goods_id)
			if(!findResult){
				state.cartInfo.push(goods)
			}else{
				findResult.goods_count++
			}
			this.commit('saveToStorage')
		 },
		 updateGoodsState(state,goods){
			let findResutl =  state.cartInfo.find(item=>item.goods_id === goods.goods_id)
			if(findResutl){
				findResutl.goods_state = goods.goods_state
				//数据持久化
				this.commit('saveToStorage')
			}
		 },
		 updateGoodsCount(state,goods){
			let findResutl =  state.cartInfo.find(item=>item.goods_id === goods.goods_id)
			if(findResutl){
				findResutl.goods_count = goods.goods_count
				//数据持久化
				this.commit('saveToStorage')
			}
		 },
		 deleteGoods(state,goods){
		 			state.cartInfo = state.cartInfo.filter(item => item.goods_id != goods.goods_id)
					//数据持久化
					this.commit('saveToStorage')
		 },
		 
	},
	actions: {

	}
}
